package com.demo.utils;
import com.demo.service.UserService;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.runtime.GStringImpl;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 计算工具类
 */
@Component
public class ComputingUtils implements ApplicationContextAware {

    private static Logger LOGGER= Logger.getLogger(ComputingUtils.class);

    private static ApplicationContext context;

    private static final CompilerConfiguration CONFIG;

    //公式计算结果对的缓存时间
    private static final Cache<String, Object> COMPUTING_CACHE = CacheBuilder.newBuilder().maximumSize(3000)
            .expireAfterAccess(1, TimeUnit.DAYS).build();
    static{
        CONFIG =  new CompilerConfiguration();
        //读取groovy函数文件初始化加载一些函数
       /* try(BufferedReader reader=new BufferedReader(new InputStreamReader(ClassLoader.getSystemResourceAsStream("groovy/ComputingBaseUtil.groovy")))) {
            GroovyClassLoader loader = new GroovyClassLoader();
            StringBuffer stringBuffer=new StringBuffer();
            String str;
            while ((str=reader.readLine())!=null){
                stringBuffer.append(str+"\n");
            }
            Class cls=loader.parseClass(stringBuffer.toString());
            CONFIG.setScriptBaseClass(cls.getName());
        } catch (Exception e) {
            LOGGER.error("构造计算BaseClass异常！",e);
        }*/
    }

    private ComputingUtils(){

    }

    /**
     * 初始化Binding，设置所有Properties
     * @return
     */
    public static Binding initProperties(){
        Binding bind=new Binding();
        //可以设置bean 对象等当Property
        NumberFormat ccyFormat = NumberFormat.getNumberInstance();
        ccyFormat.setMaximumFractionDigits(20);
        bind.setProperty("ccyFormat", ccyFormat);
        bind.setProperty("userService",context.getBean(UserService.class));
        //设置变量
        bind.setVariable("data",null);
        return bind;
    }


    /**
     * 清除缓存
     */
    public static void clearCache(){
        COMPUTING_CACHE.invalidateAll();
    }


    /**
     * 最新构建GroovyShell
     * @return
     */
    public static GroovyShell buildNewGroovyShell(){
        try{
            GroovyClassLoader loader;
            if ((loader = (GroovyClassLoader)COMPUTING_CACHE.getIfPresent("BASE_CLASS_HEAD")) == null) {
                StringBuffer stringBuffer=new StringBuffer();
                loader=new GroovyClassLoader();
                loader.parseClass("ComputingBaseUtil.groovy文件所有的字符串拼接好,可以直接读取文件，也可以直接存数据库然后读取出来");
                COMPUTING_CACHE.put("BASE_CLASS_HEAD", loader);
            }
            CONFIG.setScriptBaseClass("groovy.ComputingBaseUtil");
            return new GroovyShell(loader,initProperties(),CONFIG);
        }catch (Exception e){
            LOGGER.warn("buildTrialGroovyShell error :",e);
            throw new RuntimeException("buildTrialGroovyShell:"+e.getMessage());
        }
    }

    /**
     * 构建GroovyShell
     * @return
     */
    public static GroovyShell buildGroovyShell(){
        return new GroovyShell(initProperties(),CONFIG);
    }



    /**
     * 构建GroovyShell，同时put参数
     * @param variables
     * @return
     */
    public static GroovyShell buildGroovyShell(Map<String,Object> variables){
        GroovyShell shell=buildGroovyShell();
        setVariables(variables,shell);
        return shell;
    }

    /**
     * 设置属性值
     * @param variables
     * @param shell
     */
    public static void setVariables(Map<String,Object> variables,GroovyShell shell){
        if(shell!=null&&variables!=null&&!variables.isEmpty()){
            for (Map.Entry<String, Object> entry : variables.entrySet()) {
                setVariable(entry.getKey(),entry.getValue(),shell);
            }
        }
    }

    /**
     * 设置属性值
     * @param key
     * @param value
     * @param shell
     */
    public static void setVariable(String key,Object value,GroovyShell shell){
        Binding binding=shell.getContext();
        binding.setVariable(key,value);
    }


    /**
     * 最新执行计算表达式
     * @param expression
     * @param shell
     * @return
     */
    public static Object evaluate(String expression, GroovyShell shell) {
        String key = DigestUtils.sha512Hex(expression);
        Class<Script> scriptClass= (Class<Script>)COMPUTING_CACHE.getIfPresent(key);
        if ( scriptClass == null) {
            synchronized (key.intern()) {
                scriptClass = (Class<Script>)COMPUTING_CACHE.getIfPresent(key);
                if ( scriptClass == null) {
                    scriptClass=shell.getClassLoader().parseClass(expression);
                    COMPUTING_CACHE.put(key, scriptClass);
                }
            }
        }
        Object obj;
        Script script= InvokerHelper.createScript(scriptClass,shell.getContext());
        obj = script.run();
        if (obj instanceof GStringImpl) {
            return obj.toString();
        }
        return obj;
    }

    /**
     * 执行计算表达式 如果返回的时map查看map中是否含有key 有则只返回map中key对应的value
     * @param expression
     * @param shell
     * @return
     */
    public static Object evaluateFromMap(String expression, GroovyShell shell,String key) {
        Object obj=evaluate(expression,shell);
        if(obj instanceof Map){
            Map<String,Object> map=(Map)obj;
            if(map.containsKey(key)){
                obj=map.get(key);
            }
        }
        return obj;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context=applicationContext;
    }
}
